<!-- 数据整合 -->
<template>
  <div class="dataintergt">
    <el-container>
      <el-aside>
        <el-button type="primary" size="small" style="width: 100%;" @click="newShowClicksMsg">添加接口</el-button>
        <p style="margin: 5px 0;"></p>
        <el-tree :default-expand-all="true" :data="TreeData" :props="DataProps" @node-click="handleNodeClick">
          <template v-slot="{ node, data }">
            <el-tooltip :content="data.userApiName" placement="top">
              <span class="word-break">{{ node.label }}</span>
            </el-tooltip>
          </template>
        </el-tree>
      </el-aside>
      <el-main class="contain">
        <template v-if="!isShowDetail">
          <div class="datain_main">
            <div class="datain_main_box">
              <p class="_main_box_title">新建接口</p>
              <div class="select_list">
                <dl>
                  <dd>API名称：</dd>
                  <dd>
                    <el-input v-model.trim="ApiName" style="width: 300px;" placeholder="请输入api名称"></el-input>
                  </dd>
                </dl>
                <dl>
                  <dd>GET：</dd>
                  <dd>
                    <el-select v-model="apiInfoId" style="width: 300px;">
                      <el-option v-for="(item, li) in GetAllDataListPage" :key="item.apiInfoId"
                        :label="item.requestMethod" :value="item.apiInfoId" @click="TableDataListPage(item)" />
                    </el-select>
                  </dd>
                </dl>
                <dl>
                  <dd>供应商：</dd>
                  <dd>
                    {{ ShowClicksMsg.supplier }}
                  </dd>
                </dl>
              </div>
            </div>
            <div class="datain_main_box">
              <p class="_main_box_title">请求参数</p>
              <el-tabs type="border-card">
                <el-tab-pane label="Params">
                  <el-table :data="ShowClicksMsg.requestParams" border style="margin: 0 auto;">
                    <el-table-column prop="fieldName" label=" Path参数" />
                    <el-table-column prop="fieldTypeDesc" label="类型" />
                    <el-table-column prop="remark" label=" 说明" />
                  </el-table>
                </el-tab-pane>
                <el-tab-pane label="Auth">
                  <el-row :gutter="20">
                    <el-col :span="12" :offset="6">
                      类型：
                      <el-select v-model="typevalue" style="width: 300px;">
                        <el-option v-for="(item, li) in ShowClicksMsg.authType" :key="li" :label="item.selectContent"
                          :value="item.selectId" @click="TabKey = item.selectId" />
                      </el-select>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20" style="margin-top: 15px;">
                    <el-col :span="12" :offset="6">
                      <div v-if="typevalue == '2'">KEY：{{ ShowClicksMsg.apiKey }}</div>
                      <div v-else>KEY：</div>
                    </el-col>
                  </el-row>
                </el-tab-pane>
              </el-tabs>
            </div>
            <div class="datain_main_box">
              <p class="_main_box_title">返回响应</p>
              <el-tabs type="border-card">
                <el-tab-pane label="成功（200）">
                  <div style="margin-top: 10px;">
                    <span style="color: #409Eff;margin-left: 10px;font-size: 14px;">选择根节点：</span>
                    <el-select v-model="selectParams" multiple @change="handleChangeParams()" style="width:80%">
                      <el-option v-for="item in ShowClicksMsg.respondBody" :key="item.fieldName" :label="item.fieldName"
                        :value="item.fieldName" />
                    </el-select>
                  </div>
                  <el-table :data="pathSelectList">
                    <el-table-column prop="fieldName" label="根节点" min-width="120">
                    </el-table-column>
                    <el-table-column prop="fieldTypeDesc" label="object" min-width="200">
                      <template #default="scope">
                        <el-select v-model="scope.row.fieldTypeDesc">
                          <el-option v-for=" item in pathTypeList" :key="item" :label="item" :value="item" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="说明" min-width="120">
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <el-tab-pane label="公共响应2">
                  <el-table :data="CommonStatic" border style="margin: 0 auto;">
                    <el-table-column prop="name" label="名称" />
                    <el-table-column prop="static" label="HTTP状态码" />
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </div>
            <div class="datain_main_box" v-if="showRespond">
              <p class="_main_box_title">响应预览</p>
              <el-scrollbar height="300px">
                {{ ShowClicksMsg.respondData }}
              </el-scrollbar>
              <!-- </div> -->
            </div>
          </div>
          <p class="subtim_save">
            <el-button type="primary" @click="showParams()" :loading="BtnLoading">生成预览</el-button>
            <el-button type="danger" @click="DeleteShowClicksMsg()" :loading="BtnLoading">删除预览</el-button>
            <el-button type="primary" @click="SaveApiMessage()" :loading="BtnLoading">保存</el-button>
          </p>
        </template>
        <template v-else>
          <div class="main">
            <PureTableBar class="list_hei">
              <template v-slot="{ size, checkList }">
                <pure-table border align-whole="center" showOverflowTooltip table-layout="auto" :data="dataList"
                  :columns="columns" :pagination="pagination" max-height="650" @current-change="handleCurrentChange"
                  @size-change="handleSizeChange" :header-cell-style="{
                    background: 'var(--el-table-row-hover-bg-color)',
                    color: 'var(--el-text-color-primary)'
                  }">
                </pure-table>
              </template>
            </PureTableBar>
          </div>
        </template>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { PureTableBar } from "@/components/RePureTableBar";
import qs from 'qs'
import { type PaginationProps } from "@pureadmin/table";
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, FormInstance } from "element-plus";
import { GetDataIntegrationPage, AddOrUpdataBankAPIInfo, GetApiInfoList, GenerateRespondDataPreview, GetApiInterfaceDataInfo } from "@/api/stu/bankBigData";
const route = useRoute();
// 切换认证方式
const TabKey = ref<any>("")
// 全部数据信息
const selectParams = ref([])
const isShowDetail = ref(false)
const GetAllDataListPage = ref<any>();
const columnHead = ref([])
const selectId = ref()
const pathSelectList = ref([]) //参数列表
const pathTypeList = ref([]) //参数选项类型列表
const apiInfoId = ref()
const showRespond = ref(false)
const ShowClicksMsg = ref<any>({
  requestMethod: "",
  userApiInfoId: "",
  requestParams: [],
  respondBody: [],
  respondData: "",
  supplier: "",
  authType: [],
  apiKey: ""
});
const CommonStatic = [
  {
    name: "记录不存在",
    static: "404"
  }, {
    name: "参数不正确",
    static: "400"
  }
]


const columns = ref()
const BtnLoading = ref<boolean>(false)
const ApiName = ref<string>("");
const typevalue = ref<string>("");
interface Tree {
  userApiName: string
  children?: Tree[]
}

const dataList = ref([])
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true,
  pageSizes: [5, 10, 30],
});



const TreeData = ref<Tree[]>([
  {
    userApiName: '外部大数据接口',
    children: [],
  },
])

const DataProps = {
  children: 'children',
  label: 'userApiName',
}

// 切换查看接口数据
function TableDataListPage(row) {
  ShowClicksMsg.value = row;
  ShowClicksMsg.value.respondData = ''
  pathSelectList.value = []
  selectParams.value = []
  pathTypeList.value = row.fieldTypeDescList
}


//清空新建
function newShowClicksMsg() {
  TabKey.value = ''
  ApiName.value = ""
  apiInfoId.value = ""
  typevalue.value = ''
  ShowClicksMsg.value = {
    requestMethod: "",
    requestParams: "",
    userApiInfoId: "",
    respondBody: "",
    respondData: "",
    supplier: "",
    apiKey: ""
  };
  showRespond.value = false;
  pathSelectList.value = []
  selectParams.value = []
  isShowDetail.value = false
}
// 清空预览内容
function DeleteShowClicksMsg() {
  ShowClicksMsg.value.respondData = ''
  showRespond.value = false;
  BtnLoading.value = true;
  OUTBtnLoding()
}

// 添加接口信息
async function SaveApiMessage() {
  if (apiInfoId.value == '' || apiInfoId.value == null) {
    ElMessage.warning('请先选择生成预览的接口')
    return
  }
  if (ApiName.value == '') {
    ElMessage.warning('请填写要添加的API名称')
    return
  }
  if (TabKey.value == '') {
    ElMessage.warning('请选择请求参数类型')
    return
  }
  const data = {
    userApiName: ApiName.value,
    taskId: route.query.taskId,
    planId: route.query.planId,
    apiInfoId: apiInfoId.value,
    apiKey: TabKey.value == 1 ? '' : ShowClicksMsg.value.apiKey,
    userApiInfoId: ShowClicksMsg.value.userApiInfoId || "",
    auth: TabKey.value || "1",
    fieldInfos: pathSelectList.value,
    respondData: ShowClicksMsg.value.respondData,
  };
  BtnLoading.value = true
  data.studentAnswer = JSON.stringify(data)
  const respone = await AddOrUpdataBankAPIInfo(data);
  OUTBtnLoding()
  if (respone.success) {
    ElMessage.success(respone.msg);
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    };
    const respone1 = await GetApiInfoList(data);
    if (respone1.success) {
      TreeData.value[0].children = respone1.data
      handleNodeClick(TreeData.value[0].children[TreeData.value[0].children.length - 1])
    } else {
      ElMessage.error(respone1.msg);
    }
  } else {
    ElMessage.error(respone.msg);
  }
}

// 获取接口数据
async function GetApiData() {
  const respone = await GetDataIntegrationPage();
  GetAllDataListPage.value = respone.data;
}

// 获取左侧api接口菜单
async function GetApiLftInfoList() {
  const data = {
    taskId: route.query.taskId,
    planId: route.query.planId,
  };
  const respone = await GetApiInfoList(data);
  TreeData.value[0].children = respone.data
}


function handleChangeParams() {
  console.log(selectParams.value);

  // 遍历selectParams.value
  selectParams.value.forEach(a => {
    // 检查pathSelectList.value中是否存在与selectParams.value相同的fieldName
    const existingItemIndex = pathSelectList.value.findIndex(item => item.fieldName === a);
    if (existingItemIndex == -1) {
      pathSelectList.value.push({
        fieldName: a,
        fieldTypeDesc: '',
        remark: ShowClicksMsg.value.respondBody.find(item => item.fieldName === a).remark,
        sortNo: ShowClicksMsg.value.respondBody.find(item => item.fieldName === a).sortNo
      });
    }
    // 检查是否有需要移除的项
    pathSelectList.value = pathSelectList.value.filter(item => selectParams.value.includes(item.fieldName));
  })
}

async function showParams() {
  if (apiInfoId.value == '' || apiInfoId.value == null) {
    ElMessage.warning('请先选择生成预览的接口')
    return
  }
  let data = {
    apiInfoId: apiInfoId.value,
    fieldInfos: pathSelectList.value
  }
  BtnLoading.value = true;
  let res = await GenerateRespondDataPreview(data)
  OUTBtnLoding()
  if (res.success) {
    ShowClicksMsg.value.respondData = res.data
    showRespond.value = true;
  } else {
    ElMessage.error(res.msg);
  }
}



//获取详情数据
async function handleNodeClick(row) {
  console.log(row)
  if (row.apiInfoId) {
    columns.value = []
    selectId.value = row.userApiInfoId
    columnHead.value = JSON.parse(row.respondBody)
    columnHead.value = columnHead.value.sort((a, b) => a.sortNo - b.sortNo);
    columnHead.value = columnHead.value.filter(item => item.FieldName !== "ID");
    console.log(columnHead.value);
    columns.value = columnHead.value.map(item => {
      return { prop: item.FieldName, label: item.Remark, minWidth: 180 };
    });
    columns.value.unshift({
      label: "序号",
      type: "index",
      width: 90
    })
    isShowDetail.value = true
  }
}
async function getList() {
  const data = {
    taskId: route.query.taskId,
    planId: route.query.planId,
    pageIndex: pagination.currentPage,
    pageCount: pagination.pageSize,
    userApiInfoIds: selectId.value
  };
  const respone = await GetApiInterfaceDataInfo(data);
  if (respone.success) {
    pagination.total = respone.data.TotalCount;
    dataList.value = respone.data.Items;
    selectParams.value = []
  } else {
    ElMessage.error(respone.msg);
  }
}

function OUTBtnLoding() {
  setTimeout(() => {
    BtnLoading.value = false
  }, 1000)
}

function handleSizeChange() {
  getList()
}

function handleCurrentChange() {
  getList()
}
onMounted(() => {
  // 获取接口数据
  GetApiData();
  GetApiLftInfoList()
  getList()
  ElMessage.warning('操作该步骤时请勿使用浏览器翻译！')
})
</script>

<style lang="scss" scoped>
@import url(@/style/DataIntegration.scss);
@import url(@/style/CreditComm.scss);


.iocn {
  width: 60px;
  font-size: 20px;
  display: inline-block;
  padding: 15px;
  color: #409Eff;
}

.contain::-webkit-scrollbar {
  display: none !important;
}

.word-break {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
